package sginUp;

import view.GameFrame;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;

public class SginUp extends JFrame implements ActionListener {
    JTextField usernameText = new JTextField(20);//用户名
    JPasswordField jPasswordField = new JPasswordField(20) ;//密码


    public SginUp() {
        //初始化界面
        InitFrame();
        //初始化菜单
        InitMenu();
        //显示
        this.setVisible(true);
    }

    //初始换界面
    public void InitFrame() {
        //1.设置界面的大小
        this.setSize(350, 200);
        //2.设置界面的标题
        this.setTitle("用户登录");
        //3.设置界面置顶
        this.setAlwaysOnTop(true);
        //4.设置界面居中
        this.setLocationRelativeTo(null);
        //5.设置关闭模式
        this.setDefaultCloseOperation(2);
    }

    //初始化菜单
    public void InitMenu() {
        this.setLayout(null);
        //创建用户名
        JLabel username = new JLabel("用户名:");
        username.setBounds(10, 20, 80, 25);
        this.add(username);

        usernameText.setBounds(100, 20, 165, 25);
        this.add(usernameText);

        //创建密码
        JLabel password = new JLabel("密码:");
        password.setBounds(10, 50, 80, 25);
        this.add(password);

        jPasswordField.setBounds(100, 50, 165, 25);
        this.add(jPasswordField);


        //创建登录按钮
        JButton registerButton = new JButton("登录");
        registerButton.setBounds(140, 120, 80, 25);
        registerButton.addActionListener(this);
        this.add(registerButton);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String username = usernameText.getText();
        String password = new String(jPasswordField.getText());
       if(getUsernameFromFile("UserInfo.txt",username,password)){
           setVisible(false);
           new GameFrame();
       }else{
           JOptionPane.showMessageDialog(this, "                    用户名或密码有错误!","出错啦！",JOptionPane.PLAIN_MESSAGE);
       }

    }

    //判断用户名,用户密码是否正确
    public boolean getUsernameFromFile(String filePath, String name,String password) {
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(";");
                if (parts.length > 0) {
                    if ((parts[0].equals(name))&&(parts[1].equals(password))) {
                        return true;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

}
